package com.zoe.onelink.auth.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.zoe.onelink.common.exception.PermissionException;
import com.zoe.onelink.upms.common.entity.UserInfo;
import com.zoe.onelink.upms.common.service.OneLinkTokenStore;
import com.zoe.onelink.upms.common.utils.UpmsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2018</p>
 * <p>公司: 智业软件</p>
 *
 * @author LinHongKai
 * @date 2022-03-28 11:53
 */
@Slf4j
@RequiredArgsConstructor
public class OneLinkPermissionService {

    /**
     * 判断接口是否有任意xxx，xxx的菜单权限
     * @param permissions 权限
     * @return {boolean}
     */
    public boolean hasPermission(String... permissions) {
        if (ArrayUtil.isEmpty(permissions)) {
            return true;
        }
        UserInfo userInfo = UpmsUtils.getUser();
        if(userInfo == null){
            throw new PermissionException();
        }
        log.info("用户：【username：{}，name：{}】，校验权限标识：{}", userInfo.getUsername(), userInfo.getName(), permissions);
        // 超级管理员，拥有全部权限
        if(userInfo.getIsAdministrator()){
            log.info("用户：【username：{}，name：{}】，为超级管理员，拥有全部权限", userInfo.getUsername(), userInfo.getName(), permissions);
            return true;
        }

        List<String> authorities = UpmsUtils.getUserPermissions();
        if(CollectionUtil.isEmpty(authorities)){
            log.info("用户：【username：{}，name：{}】，权限集合为空，无任何权限", userInfo.getUsername(), userInfo.getName(), permissions);
            throw new PermissionException();
        }
        boolean isAllowed = authorities.stream().filter(StringUtils::hasText)
                .anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
        if(!isAllowed){
            log.info("【权限校验失败】：用户：【username：{}，name：{}】，校验权限：{}，权限集合为：{}",
                    userInfo.getUsername(), userInfo.getName(), permissions, authorities);
            throw new PermissionException();
        }
        return true;
    }
}
